package cn.jcet.config.shiro;

import cn.jcet.constants.HttpStatus;
import cn.jcet.vo.AjaxResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 鲜磊
 * @Date 2021/1/18 21:14
 * 重新拦截器
 */
public class ShiroLoginFilter extends FormAuthenticationFilter {

    /**
     * 在访问controller前判断是否登录，返回json，不进行重定向
     * @param request
     * @param response
     * @return true 继续向下执行，false改filter过滤器已经处理，不在继续执行其他过滤器
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
         HttpServletResponse httpServletResponse = (HttpServletResponse) response;
         // headers 头信息
         httpServletResponse.setCharacterEncoding("utf-8");
         httpServletResponse.setContentType("application/json");
         // 创建返回信息类
        AjaxResult ajaxResult = AjaxResult.fail();
        // 状态未被授权
        ajaxResult.put("code",HttpStatus.UNAUTHORIZED);
        // 提示信息
        ajaxResult.put("msg","登录认证失败，请重新登录！");
        // 返回json数据
        httpServletResponse.getWriter().write(JSON.toJSONString(ajaxResult).toString());
        return false;
    }
}
